<template>
  <div class="mt-1">
    <van-form>
      <van-field
        clickable
        readonly
        is-link
        arrow-direction="down"
        v-model="value"
        label="工厂代码"
        :value="value"
        @click="showPicker = true"
        placeholder="请选择工厂代码"
      >
      </van-field>
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          title="工厂代码"
          show-toolbar
          :columns="plantcode"
          @cancel="showPicker = false"
          @confirm="onAffirm"
        />
      </van-popup>
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
        placeholder="请扫描拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 60vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row
        type="flex"
        gutter="30"
        justify="center"
        style="margin-top: 1rem"
      >
        <van-col span="9">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <!-- <van-col span="7"
          ><van-button type="info" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        > -->
        <van-col span="9"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-data-z-s :ShowDataA="ShowData" @get-val="Sure" />
      </van-popup>
    </van-form>
    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="请输入要修改的数量"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入数量"
      />
    </van-dialog>
  </div>
</template>

<script>
import { getpickplant } from "../assets/api/get";
import { InformationSubmit } from "../assets/api/post";
import { AgGridVue } from "ag-grid-vue";
import { AgGrid } from "../minx/AgGrid";
import { toast, parseQRCode } from "../untils/commion";
import ShowDataZS from "../components/ShowData.vue";

export default {
  components: { AgGridVue, ShowDataZS },
  mixins: [AgGrid],
  data() {
    return {
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      titles: new Map().set(4, "STO临时收货"),
      ShowStatue: false,
      type: null,
      location: "", //传回来的库位
      code: "", //拍码
      value: "CN01", //所选工厂
      showPicker: false,
      plantcode: [], //工厂代码数组
      copyplantcode: [], //不重复的工厂代码
      columnDefs: [
        { headerName: "物料", field: "materialCode", flex: 1.5 },
        { headerName: "拍号", field: "palletNo", flex: 2 },
        { headerName: "数量", field: "quantity", flex: 1.5 },
      ],
      rowData: [],
      detailData: [], //提交的详细数据
      ShowData: {}, //展示的数据
      Res: {}, //复制获得的解析数据
    };
  },
  watch: {
    code(newValue) {
      if (this.value) {
        if (newValue.length > 9) {
          let res = parseQRCode(newValue, this.value);
          this.Res = JSON.parse(JSON.stringify(res));
          if (res) {
            if (!this.rowData.find((it) => it.palletNo == res.palletNo)) {
              this.ShowData = JSON.parse(JSON.stringify(res));
              // 改变日期格式
              let SC = "20" + this.ShowData.prodDate;
              let YX = "20" + this.ShowData.BBD;
              this.ShowData.prodDate =
                SC.substring(0, 4) +
                "-" +
                SC.substring(4, 6) +
                "-" +
                SC.substring(6, 8);
              this.ShowData.BBD =
                YX.substring(0, 4) +
                "-" +
                YX.substring(4, 6) +
                "-" +
                YX.substring(6, 8);

              if (this.ShowData) {
                this.ShowStatue = true;
                this.rowData.push(res);
              }
              res = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
      } else {
        toast("请选择工厂");
      }
      this.code = "";
    },
  },
  methods: {
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //界面标题
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    //传回来把组件关闭
    Sure(val) {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.location = val;
      this.Res.StorehouseName = this.location;
      this.getOther();
      this.$refs.code.focus();
    },
    //日期格式
    DateFormat(date) {
      let wholeDate = "20" + date;
      return `${wholeDate.substring(0, 4)}-${wholeDate.substring(
        4,
        6
      )}-${wholeDate.substring(6, 8)}`;
    },
    //主列表数据
    getOther() {
      let SCdata = this.DateFormat(this.Res.prodDate);
      let YXdata = this.DateFormat(this.Res.BBD);
      this.detailData.push({
        UniqueId: this.Res.palletNo,
        SupplierId: this.Res.commerialVendor,
        Num: this.Res.quantity,
        Unit: this.Res.uom,
        BatchNO: this.Res.batchCod,
        ProductionDate: SCdata,
        ExpDate: YXdata,
        ProducerId: this.Res.gsVendor,
        PONO: this.Res.poNo,
        BaoJanNo: this.Res.inspectionNumber,
        SupplyBatchNO: this.Res.vendorBatch,
        GuiGe: this.Res.materialCfg,
        ProductId: this.Res.materialCode,
        StorehouseName: this.Res.StorehouseName,
        WareHouseId: "0020",
        WareHouseName: "0020",
        InventoryStatus: "U",
      });
    },
    //删除选中
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    //代码选择/确认
    onAffirm(value) {
      this.value = value;
      this.showPicker = false;
    },
    //工厂代码数组分类
    getPlantCode(PL) {
      let _this = this;
      PL.map((item) => {
        _this.copyplantcode.push(item.plantcode);
      });
      for (var j in this.copyplantcode) {
        if (this.plantcode.indexOf(this.copyplantcode[j]) == -1) {
          this.plantcode.push(this.copyplantcode[j]);
        }
      }
    },
    //向后台提交数据
    async onSubmit() {
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        let type = "TemporaryIn";
        let submitData = {
          WareHouseId: "0020",
          WareHouseName: "0020",
          CreatedId: JSON.parse(localStorage.getItem("userid")),
          BillType: "TemporaryIn",
          BillTypeName: "STO临时收货",
          CreatedName: JSON.parse(localStorage.getItem("username")),
          Plant: this.value,
          InventoryStatus: "U",
          InDate: this.getNowDate(),
        };

        let res = await InformationSubmit(
          type,
          JSON.stringify(submitData),
          JSON.stringify(this.detailData)
        );

        if (res.d.state == "success") {
          this.rowData = [];
          this.submitData = [];
          this.detailData = [];
          this.$refs.code.focus();
          if (this.rowData.length == 0) {
            this.$toast(res.d.message);
          }
        } else {
          this.$toast(res.d.message);
        }
      }
    },
    //自动获取工厂信息
    async getBusinessInfo() {
      let res = await getpickplant();
      if (res.status == 200) {
        this.getPlantCode(res.data.data);
      } else {
        toast("后台发生错误，请与管理员联系");
      }
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    // //点击弹出修改数量弹窗
    // updateNum() {
    //   this.selectDate = this.gridApi.getSelectedRows();
    //   if (this.selectDate[0] == null) {
    //     this.$toast("请选择要修改的数据");
    //   } else {
    //     this.ifShowUpdateNum = true;
    //   }
    // },
    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "") {
        this.$toast("未输入数量无法修改");
      } else {
        this.selectDate[0].quantity = this.needUpdateNum;
        this.gridApi.applyTransaction({ update: this.selectDate });
        this.detailData.forEach((item) => {
          if (this.selectDate[0].batchCod == item.BatchNO) {
            item.Num = Number(this.needUpdateNum);
          }
        });
        this.needUpdateNum = "";
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.$refs.code.focus();
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.getBusinessInfo();
    this.closeEnter();
  },
};
</script>

<style lang="less" scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
</style>